<template>
  <BasicModal
    v-bind="$attrs"
    :title="t('tb.commandDispatch')"
    width="520px"
    :ok-text="t('tb.commandDispatch')"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <div class="command-dispatch-modal">
      <div class="selected-count">
        {{ t('tb.commandSelectedHint', { count: selectedCount }) }}
      </div>
      <Form layout="vertical">
        <FormItem :label="t('tb.commandField')">
          <Select v-model:value="formState.method">
            <Select.Option v-for="option in commandOptions" :key="option.value || 'custom'" :value="option.value">
              {{ option.label }}
            </Select.Option>
          </Select>
        </FormItem>
        <FormItem :label="t('tb.commandParamsField')">
          <Input.TextArea
            v-model:value="formState.params"
            :placeholder="t('tb.commandParamsPlaceholder')"
            :auto-size="{ minRows: 4, maxRows: 8 }"
            :disabled="isFixedParam"
          />
        </FormItem>
      </Form>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, reactive, ref, watch } from 'vue';
  import { Form, Select, Input } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { deviceCommandDispatch } from '/@/api/tb/device';

  const { t } = useI18n('tb');
  const { createConfirm, showMessage } = useMessage();
  const FormItem = Form.Item;

  interface CommandDispatchModalContext {
    deviceIds: string[];
  }

  const emit = defineEmits(['success', 'register']);

  const formState = reactive({
    method: 'shutdown',
    params: '',
  });

  const selectedDeviceIds = ref<string[]>([]);

  const commandOptions = computed(() => [
    { label: t('tb.commandOptionShutdown'), value: 'shutdown' },
    { label: t('tb.commandOptionReboot'), value: 'reboot' },
    { label: t('tb.commandOptionCustom'), value: '' },
  ]);

  const selectedCount = computed(() => selectedDeviceIds.value.length);
  const isFixedParam = computed(() => ['shutdown', 'reboot'].includes(formState.method));

  watch(
    () => formState.method,
    (method, prev) => {
      if (['shutdown', 'reboot'].includes(method)) {
        formState.params = '';
        return;
      }
      if (['shutdown', 'reboot'].includes(prev ?? '')) {
        formState.params = '';
      }
    },
    { immediate: true },
  );

  const [registerModal, { setModalProps, closeModal }] = useModalInner((data?: CommandDispatchModalContext) => {
    selectedDeviceIds.value = data?.deviceIds ?? [];
    formState.method = 'shutdown';
  });

  function handleSubmit() {
    if (selectedCount.value === 0) {
      showMessage(t('tb.commandSelectedHint', { count: 0 }), 'warning');
      return;
    }

    createConfirm({
      iconType: 'warning',
      title: t('tb.commandConfirmTitle'),
      content: t('tb.commandConfirmDesc', { count: selectedCount.value }),
      onOk: async () => {
        await dispatchCommand();
      },
    });
  }

  async function dispatchCommand() {
    try {
      setModalProps({ confirmLoading: true });
      await deviceCommandDispatch({
        deviceIds: selectedDeviceIds.value,
        deviceRpcCommand: {
          method: formState.method,
          params: formState.params || '',
        },
      });
      showMessage(t('tb.commandSuccess'));
      emit('success');
      closeModal();
    } catch (error: any) {
      const message = error?.message || t('tb.commandFailed');
      showMessage(message, 'error');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  .command-dispatch-modal {
    .selected-count {
      margin-bottom: 16px;
      color: var(--text-color-secondary, #666);
    }
  }
</style>
